#!-*- encoding:utf8 -*-
from django.template import Template, Context, RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from django.contrib.auth.decorators import user_passes_test, login_required
from django.http import Http404, HttpResponseRedirect, HttpResponse

from newosmp.host.models import Host, Product
from newosmp.monitor.models import Monitor
from newosmp.alert.models import Alert, AlertReceive
from newosmp.util import commom
from newosmp import settings
from django.db.models import Q

import time, datetime, json
import settings


@login_required
def index(request):
    lastweek = datetime.datetime.today() - datetime.timedelta(days=7)
#    if id == '-1':
    page = int(request.GET.get('page', '1'))
    alert = Alert.objects.select_related(depth=1).all()
    num = settings.PAGE

    (alert, page_list, page_num) = commom.pagination(alert, page, num)

    (page_up, page_down) = commom.getPage(page, page_num) #上下页
#                    mid__pid__in = request.session['auth_pids'], 
#            timestamp__gte = lastweek).order_by('-timestamp')
#    else:
#        alerts = Alert.objects.select_related(depth=1).filter(
#                mid = id, timestamp__gte = lastweek).order_by('-timestamp')
#    print alert
#    if merge == 'on':
#        uniqAlert = []
#        uniqKey= {}
#        for elem in alerts:
#            mid = str(elem.mid.id)
#            if uniqKey.has_key(mid):
#                uniqKey[mid] += 1
#            else:
#                uniqKey[mid] = 1
#                uniqAlert.append(elem)
#        for elem in uniqAlert:
#            mid = str(elem.mid.id)
#            elem.num = uniqKey[mid]
#    else:
#        uniqAlert = alerts

    return render_to_response("alert.html", locals())


@login_required
def replay(request):
    id = request.GET.get('id','')
    if not id:
        id = request.POST.get('id','')
    print id
    id = int(id)
    alert = Alert.objects.get(id=id)
#    print alter
    if request.method == "POST":
        reason = request.POST.get('reason')
        rtype = request.POST.get('rtype')
        alert.reason = reason
        alert.rtype = rtype
        alert.uid = request.user.username
        alert.save()
        return HttpResponseRedirect('/alert/reason?id=%s' % id)
    else:
        mid = alert.mid.id
        monitor = Monitor.objects.get(id=mid)
        alert.host = monitor.hid
        return render_to_response('alertreplay.html', locals())


@login_required
def reason(request):
    id = request.GET.get('id')
    alert = Alert.objects.get(id=id)
    mid = alert.mid.id
    monitor = Monitor.objects.get(id=mid)
    alert.host = monitor.hid
    return render_to_response('alertreason.html', locals())


def people(request):
    alert_user = User.objects.all()
    return render_to_response("alertpeople.html", locals())

def reset(request):
    uid = int(request.GET.get('id', 1))
    alert = AlertReceive.objects.filter(uid=uid)
    monitor = Monitor.objects.all()
    alert_mid = []
    for a in alert:
        alert_mid.append(a.mid.id)
    unset_monitor = []
    for m in monitor:
        if m.id in alert_mid:
            continue
        else:
            unset_monitor.append(m)
    return render_to_response("alertreset.html", locals())

def delete(request):
    id = int(request.GET.get('id', -1))
    if id == -1:
        ret = {'flag': 'false'}
    else:
        alert = AlertReceive.objects.filter(id=id)
        alert.delete()
        ret = {'flag': 'true'}
        #通知daemon端
        
    return HttpResponse(json.dumps(ret))

@login_required
def search(request):
    if request.method == 'POST':
        key = request.POST.get('key', '')#原因 处理人 主机 监控项 
        if key:
            q = Q()
            q &= Q(auth_uid=uid) | Q(op_uid=uid)
            alert = Alert.objects.filter(q).order_by('-id')
        else:
            pass
    else:
        pass
    return render_to_response("alert.html", locals())


def ajaxAdd(request):
    mid = int(request.GET.get('mid', -1))
    uid = int(request.GET.get('uid', -1))
    if mid == -1 or uid == -1:
        ret = {'flag': 'false'}
    else:
        ar = AlertReceive.objects.create(
                mid=Monitor.objects.get(id=mid),
                uid=User.objects.get(id=uid),
                mode="1100")
        ar.save()

        #通知daemon端(由于速度太慢，因此改掉)

        ret = {'flag': 'true'}
    return HttpResponse(json.dumps(ret))


def ajaxReplay(request):
    ret = {'flag': 'error'}
    if request.method == 'POST':
        ids = request.POST.get('ids', '')
        rtype = request.POST.get('rtype', '')
        reason = request.POST.get('reason', '')
        if not ids.strip():
            return HttpResponse(json.dumps(ret))
        objs = Alert.objects.filter(id__in=ids.split())
        for e in objs:
            e.rtype = rtype
            e.reason = reason
            e.uid = request.user.username
            e.save()
        
        ret = {'flag': 'succ'}
        return HttpResponse(json.dumps(ret))
    else:
        return HttpResponse(json.dumps(ret))

def ajaxDel(request):
    ret = {'flag': 'error'}
    if request.method == 'POST':
        ids = request.POST.get('ids', '')
        if not ids.strip():
            return HttpResponse(json.dumps(ret))
        objs = Alert.objects.filter(id__in=ids.split())
        for e in objs:
            e.delete()
        
        ret = {'flag': 'succ'}
        return HttpResponse(json.dumps(ret))
    else:
        return HttpResponse(json.dumps(ret))

